package com.mikelouis.test.scala.proginscala.chapter28

/**
 * These equality methods are symmetric but not transitive
 * Created by yuazhu on 2/26/2015.
 */
object Points6 {

  class Point(var x: Int, var y: Int) {
    // Problematic
    override def hashCode = 41 * (41 + x) + y

    override def equals(other: Any) = other match {
      case that: Point => this.x == that.x && this.y == that.y
      case _ => false
    }
  }

  object Color extends Enumeration {
    val Red, Orange, Yellow, Green, Blue, Indigo, Violet = Value
  }

  class ColoredPoint(x: Int, y: Int, val color: Color.Value)
    extends Point(x, y) {
    // Problem: equals not transitive

    override def equals(other: Any) = other match {
      case that: ColoredPoint =>
        (this.color == that.color) && super.equals(that)
      case that: Point =>
        that equals this
      case _ =>
        false
    }
  }

  def main(args: Array[String]) {
    val p = new Point(1, 2)
    val redp = new ColoredPoint(1, 2, Color.Red)
    val bluep = new ColoredPoint(1, 2, Color.Blue)
    println(redp == p)
    println(p == bluep)
    // transitive is broken, because redp = p, p = bluep ==> redp = bluep
    println(redp == bluep)
  }

}
